package com.zwj.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwj.config.Result;
import com.zwj.pojo.User;
import com.zwj.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : 朱文杰
 * @Create 2022/8/30 21:57
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserServiceImpl userService;

    @PostMapping    //新增
    public Result<?> save(@RequestBody User user){
        if (user.getPassword() == null){
            user.setPassword("123456");
        }
        userService.insert(user);
        return Result.success();
    }


    @DeleteMapping("/{id}")    //删除
    public Result<?> delete(@PathVariable Long id){
        userService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/{id}")    //查询当前用户信息
    public Result<?> getById(@PathVariable Long id){
        return Result.success(userService.selectById(id));
    }



    @PutMapping    //修改
    public Result<?> update(@RequestBody User user){
        userService.updateById(user);
        return Result.success();
    }

    @GetMapping //查询
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(search)){
            wrapper = Wrappers.<User>lambdaQuery().like(User::getNickname, search);
        }
        Page<User> userPage = userService.selectPage(page,wrapper);
        return Result.success(userPage);
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){
        User res = userService.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if (res == null){
            return Result.error("1","用户名或密码错误");
        }
        return Result.success(res);
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user){
        User res = userService.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null){
            return Result.error("-1","用户名已被注册");
        }
        if (user.getPassword() == null){
            user.setPassword("123456");
        }
        userService.insert(user);
        return Result.success();
    }

}
